<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


    <script type="text/javascript">
        var ws;

        function WebSocketTest() {
            if ("WebSocket" in window) {
                var username = document.getElementById("username").value;
                // 打开一个 web socket
                ws = new WebSocket("ws://localhost:8080/lightpower/" + username);

                ws.onopen = function () {
                    // Web Socket 已连接上，使用 send() 方法发送数据

                    // alert("连接成功...");
                    fillData("连接成功")
                };

                ws.onmessage = function (evt) {
                    var received_msg = evt.data;
                    //  alert("数据已接收...");
                    fillData(received_msg);
                };

                ws.onclose = function () {
                    // 关闭 websocket
                    fillData("连接关闭");
                };
            } else {
                // 浏览器不支持 WebSocket
                alert("您的浏览器不支持 WebSocket!");
            }
        }

        //关闭连接
        function closeWebsocket() {
            if (ws) {
                ws.close();
            }else{
                fillData("ws没有初始化");
            }
        }


        function fillData(data) {
            document.getElementById("contents").innerHTML = data;
        }
        function sendMsg(){
            //发送消息给目标接收者
            var toUser = document.getElementById("toUser").value;//接收者
            var message = document.getElementById("neirong").value;//内容
            var msg='{"toUser":"'+toUser+'","msg":"'+message+'"}';
            ws.send(msg);//发送数据
        }
    </script>
</head>
<body>
姓名:<input id="username">
<button onclick="WebSocketTest()">连接</button>
<br>
接收者:<input id="toUser">
<br>
内容:<textarea id="neirong"></textarea>
<button onclick="sendMsg()">发送</button>
<br>
<br>
<br>
<button onclick="closeWebsocket()">关闭连接</button>

<br>
<br>
<br>
<br>
<br>
<span id="contents"></span>
</body>
</html>